<template>
  <div class="edit-page-wrap">
    <Head title="基础信息" isBack>
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
        >
          <el-form-item label="等级名称" prop="levelName">
            <el-input
              v-model.trim="ruleForm.levelName"
              placeholder="请输入等级名称"
              maxlength="8"
              clearable
            />
          </el-form-item>
          <el-form-item label="经验值要求" prop="experienceValue">
            <el-input
              v-model.trim="ruleForm.experienceValue"
              placeholder="请输入经验值要求"
              maxlength="7"
              :disabled="Boolean(id)"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="会员权益">
      <template #content>
        <el-form
          ref="ruleOtherFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="edit-form-wrap"
          v-if="!ruleForm.isDefault"
        >
          <el-form-item label="会员样式" prop="picture">
            <el-radio-group
              v-model="ruleForm.picture"
              v-for="(item, index) in LEVEL_TYPE"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="" prop="">
            <div
              class="levelStyle"
              :class="`levelStyle${ruleForm.picture}`"
            ></div>
          </el-form-item>

          <el-form-item label="权益折扣" prop="discount">
            <el-input
              v-model.trim="ruleForm.discount"
              placeholder="请输入权益折扣"
              maxlength="30"
              :disabled="Boolean(id)"
              clearable
            />
            %
          </el-form-item>
          <el-form-item label="抵扣类型" prop="type">
            <el-radio-group
              v-model="ruleForm.type"
              v-for="(item, index) in optionsS.deductionType"
              :key="index"
              :disabled="Boolean(id)"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="权益说明" prop="explainStatement">
            <el-input
              v-model.trim="ruleForm.explainStatement"
              placeholder="请输入权益说明"
              maxlength="200"
              type="textarea"
              :rows="3"
              show-word-limit
              clearable
            />
          </el-form-item>
          <el-form-item label="可用电站" prop="useType" class="has-tips">
            <el-radio-group
              v-model="ruleForm.useType"
              v-for="(item, index) in optionsS.powerStationType"
              :key="index"
              @change="handleStationType"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              <text v-if="ruleForm.useType == '0'">所有电站均参与活动</text>
              <text v-if="ruleForm.useType == '1'"
                >选定运营商后，该运营商所有的电站均参与活动，含活动期间新增的电站</text
              >
              <text v-if="ruleForm.useType == '2'"
                >选定单电站后，仅所选电站参与活动，活动期间运营商新增电站不在活动范围内</text
              >
            </div>
          </el-form-item>
          <el-form-item label="" prop="treeOrgs" v-if="ruleForm.useType == '1'">
            <QcTree
              ref="treeOrgRef"
              :setCheckedKeys="ruleForm.treeOrgs"
              :data="optionsS.org"
              :showCheckbox="true"
              :checkStrictly="true"
              @handleCheck="handleCheckOrg"
            ></QcTree>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.useType == '2'"
            label=""
            prop="treeStations"
          >
            <QcTree
              ref="treeStationRef"
              :data="optionsS.station"
              :setCheckedKeys="ruleForm.treeStations"
              :showCheckbox="true"
              @handleCheck="handleCheckStation"
            ></QcTree>
          </el-form-item>
        </el-form>
        <div class="level-tips" v-else>不享受会员权益！</div>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>
  
  <script lang="ts" setup>
import type { FormInstance, FormRules } from 'element-plus';
import Head from '@/components/head/index.vue';
import QcTree from '@/components/qcTree/index.vue';
import { addLevel, queryLevelDetail, updateLevel } from '@/service/apis/config';
import { stationTreeDataByChannel, queryCarList } from '@/service/apis/org';
import { queryDicByParent } from '@/service/apis/api';
import { IS_INT_0, IS_0_100 } from '@/utils/verify';
import { POWER_STATION_TYPE, LEVEL_TYPE } from '@/utils/dictionaries';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;
const ruleFormRef = ref<FormInstance>();
const ruleOtherFormRef = ref<FormInstance>();
const treeOrgRef = ref();

const optionsS = reactive({
  stationType: [] as any,
  userType: [] as any,
  org: [] as any,
  station: [] as any,
  deductionType: [] as any,
  powerStationType: POWER_STATION_TYPE,
});

let ruleForm = reactive({
  id: id,
  levelName: '',
  experienceValue: '',
  useType: '0',
  type: '1',
  privilegeDto: {
    discount: '',
    type: '',
    explainStatement: '',
    useType: '',
    stationList: [] as any,
  },
  discount: '',
  explainStatement: '',
  treeStations: [] as any,
  treeOrgs: [] as any,
  picture: '1',
  isDefault: false || undefined,
});
const checkTreeOrg = (rule: any, value: any, callback: any) => {
  const arr: any = [];
  const treeOrg = treeOrgRef.value?.getCheckedNodes();
  treeOrg.forEach((item: any) => {
    if (item.type !== 'CHANNEL') {
      arr.push(item.id);
    }
  });
  if (arr.length === 0) {
    callback(new Error('请选择具体的电站运营商'));
  }
  callback();
};
const rules = reactive<FormRules>({
  levelName: [{ required: true, message: '请输入等级名称', trigger: 'blur' }],
  experienceValue: [
    { required: true, message: '请输入经验值要求', trigger: 'blur' },
    {
      pattern: IS_INT_0,
      message: '经验值必须大于等于0的整数',
      trigger: 'blur',
    },
  ],
  type: [{ required: true, message: '请选择抵扣类型', trigger: 'change' }],
  discount: [
    { required: true, message: '请输入权益折扣', trigger: 'blur' },
    {
      pattern: IS_0_100,
      message: '请输入正确的权益折扣（0-100）',
      trigger: 'blur',
    },
  ],
  explainStatement: [
    { required: true, message: '请输入权益说明', trigger: 'blur' },
  ],
  useType: [{ required: true, message: '请选择可用电站', trigger: 'change' }],
  treeOrgs: [
    { required: true, message: '请选择运营商', trigger: ['blur', 'change'] },
    { validator: checkTreeOrg, trigger: ['blur', 'change'] },
  ],
  treeStations: [
    { required: true, message: '请选择电站', trigger: ['blur', 'change'] },
  ],
  picture: [{ required: true, message: '请选择会员样式', trigger: 'change' }],
});

const back = () => {
  router.go(-1);
};

// 获取电站运营商树
const getOrgs = () => {
  queryCarList({}).then((res: any) => {
    if (res) {
      optionsS.org = res;
    }
  });
};

// 获取电站树
const getStations = () => {
  stationTreeDataByChannel({ cecType: 2 }).then((res: any) => {
    if (res) {
      optionsS.station = res;
    }
  });
};

const orgId = window.localStorage.getItem('orgId') || '';
if (orgId) {
  optionsS.powerStationType = POWER_STATION_TYPE.filter(
    (item: any) => item.value !== '0'
  );
  ruleForm.useType = '1';
}
if (id) {
  queryLevelDetail({ id }).then((res: any) => {
    if (res) {
      ruleForm.levelName = res.levelName;
      ruleForm.experienceValue = res.experienceValue;
      ruleForm.picture = res.picture;
      ruleForm.isDefault = res.isDefault;
      if (!res.isDefault) {
        ruleForm.useType = res.privilege.useType;
        ruleForm.type = res.privilege.type;
        ruleForm.discount = res.privilege.discount;
        ruleForm.explainStatement = res.privilege.explainStatement;
        ruleForm.explainStatement = res.privilege.explainStatement;

        console.log(ruleForm.isDefault);

        if (ruleForm.useType === '2') {
          ruleForm.treeStations = res.privilege.stationIds.split(',');
          getStations();
        } else if (ruleForm.useType === '1') {
          ruleForm.treeOrgs = res.privilege.stationIds.split(',');
          getOrgs();
        }
      }
    }
  });
} else {
  // getOrgs();
  if (orgId) {
    getOrgs();
  }
}

queryDicByParent({
  listDtos: ['deductionType'],
}).then((res: any) => {
  optionsS.deductionType = res.deductionType;
});

const handleStationType = (val: any) => {
  if (val === '1') {
    getOrgs();
  } else if (val === '2') {
    getStations();
  }
};
const handleCheckOrg = (data: any, checkedData: any, checkedChildData: any) => {
  ruleForm.treeOrgs = checkedChildData;
  ruleOtherFormRef.value?.validateField('treeOrgs');
};
const handleCheckStation = (
  data: any,
  checkedData: any,
  checkedChildData: any
) => {
  ruleForm.treeStations = checkedChildData;
  ruleOtherFormRef.value?.validateField('treeStations');
};
const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (ruleForm.isDefault) {
    if (!ruleFormRef.value) return;
    let flag = true;
    let objError = {} as any;
    await Promise.all([
      ruleFormRef.value.validate((e: any, fields: any) => {
        flag = flag ? e : false;
        if (!e) {
          objError = { ...objError, ...fields };
        }
      }),
    ]);
    if (!flag) {
      for (const key in ruleForm) {
        if (objError[key]) {
          ruleFormRef.value.scrollToField(key);
          break;
        }
      }
      return;
    }

    if (id) {
      updateLevel(ruleForm).then((res: any) => {
        emit('clear-cache');
        back();
      });
    } else {
      delete ruleForm.isDefault;
      addLevel(ruleForm).then((res: any) => {
        emit('clear-cache');
        back();
      });
    }
  }

  if (!ruleFormRef.value || !ruleOtherFormRef.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleOtherFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleOtherFormRef.value.scrollToField(key);
        break;
      }
    }
    return;
  }

  if (ruleForm.useType === '2') {
    ruleForm.privilegeDto.stationList = ruleForm.treeStations;
  } else if (ruleForm.useType === '1') {
    // ruleForm.privilegeDto.stationList = ruleForm.treeOrgs;
    const arr: any = [];
    const treeOrg = treeOrgRef.value?.getCheckedNodes();
    treeOrg.forEach((item: any) => {
      if (item.type !== 'CHANNEL') {
        arr.push(item.id);
      }
    });
    ruleForm.privilegeDto.stationList = arr;
  }
  ruleForm.privilegeDto.discount = ruleForm.discount;
  ruleForm.privilegeDto.type = ruleForm.type;
  ruleForm.privilegeDto.explainStatement = ruleForm.explainStatement;
  ruleForm.privilegeDto.useType = ruleForm.useType;
  if (id) {
    updateLevel(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    delete ruleForm.isDefault;
    addLevel(ruleForm).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>
<style lang="scss" scoped>
.levelStyle {
  width: 331px;
  height: 139px;
  background-repeat: no-repeat;
  background-size: cover;
}
.levelStyle1 {
  background-image: url(@/assets/images/huiyuan1.png);
}
.levelStyle2 {
  background-image: url(@/assets/images/huiyuan2.png);
}
.levelStyle3 {
  background-image: url(@/assets/images/huiyuan3.png);
}
.levelStyle4 {
  background-image: url(@/assets/images/huiyuan4.png);
}
.levelStyle5 {
  background-image: url(@/assets/images/huiyuan5.png);
}
.levelStyle6 {
  background-image: url(@/assets/images/huiyuan6.png);
}
.levelStyle7 {
  background-image: url(@/assets/images/huiyuan7.png);
}
.level-tips {
  font-size: 14px;
  padding-left: 90px;
}
</style>